<?php
namespace App\Service;

use App\Models\Card\CardCouponCode;

use App\Models\Mall\MallMaster;

use Carbon\Carbon;

use App\Models\Card\CardCoupon;

use Illuminate\Support\Facades\DB;

use Illuminate\Support\Facades\Redis as Redis;

class CardService
{

    /**
     * 生成券码号
     * @param int $card_id 卡券id
     * @return int
     */
    private function createCode($card_id)
    {
        $code = '';
        while(1) {
            $code = $card_id . mt_rand(0,9) . mt_rand(0,9) . mt_rand(0,9) . mt_rand(0,9) . mt_rand(0,9) . mt_rand(0,9) . mt_rand(0,9);
            $code_data = CardCouponCode::where('barcode',$code)->first();
            if ($code_data) {
                continue;
            }
            break;
        }
        return $code;
    }

    /**
     * 发放券码
     * @param $card_data
     * @param $send_num
     * @param $pcustID
     * @param $custID
     * @param bool $is_transaction
     * @return array
     */
    public function grant( $card_data , $send_num, $pcustID , $custID , $is_transaction = true )
    {

        if ( empty( $card_data ) ) {
            return [ 'code' => 10002 , 'message'=>'缺少卡券信息' ];
        }
        if ( !ebsig_is_int( $send_num ) ) {
            return [ 'code' => 10000 , 'message'=>'卡券发放数量为空' ];
        }
        if ( !ebsig_is_int( $pcustID ) ) {
            return [ 'code' => 10001 , 'message'=>'缺少会员信息' ];
        }

        /**
         * =========================================
         *  插入活动码池子表信息
         * =========================================
         */
        $code_amount = $card_data['amount'] ; //券金额
        $discount = $card_data['discount']*100 ; //券折扣
        $limitMoney = $card_data['limit_money']; //券使用限额
        $postID = 0 ;  //商品网购号
        $goods_name = ''; //商品名称
        $product_code = ''; //商品编码
        $goods_num = 0; // 商品数量
        $marketPrice = 0; //市场价格
        $salePrice = 0 ; //商品价格
        $bill_no = '';//订单号
        $code_use_type = $card_data['card_type'];
        $member_code = ''; //会员标识
        $member_code_type = ''; //会员类型
        $sales_code = ''; //核销营业员工号
        $code_use_amount = 0; //券使用金额

        if ($card_data['card_type'] == 1) {//代金券
            $code_type = 6;
        } else if ($card_data['card_type'] == 2) {//折扣券
            $code_type = 7;
        } else if ($card_data['card_type'] == 5) {//免运费券
            $code_type = 10;
        } else {
            return [ 'code' => 10010 , 'message'=>'卡券类型有误' ];
        }

        if ($card_data['time_type'] == 1) {
            $code_startTime = $card_data['use_start_time'];
            $code_endTime = $card_data['use_end_time'];
        } else {
            $code_startTime = date('Y-m-d H:i:s',strtotime('+' .  $card_data['valid_begin_day'] . ' day'));
            $code_endTime = date('Y-m-d H:i:s',strtotime('+' . $card_data['valid_day'] . ' day',strtotime($code_startTime)));
        }

        $activityID = $card_data['card_id'];
        $activityName =$card_data['card_name'];
        $activityUUID = $card_data['uuid'];
        $start_time = $card_data['start_time'];
        $end_time = $card_data['end_time'];
        $external_code = $card_data['external_no'];
        $get_time =Carbon::now();
        $code_status = 1;
        $code_verify_type = $card_data['is_mobile_verify'] == 1 ? 1 : 2;

        //门店信息（临时）
        $mallID = $card_data['mallID'];
        if ( $mallID > 0 ) {
            $code_array = MallMaster::select('mallCode')->find( $mallID );
            $mallCode = !empty($code_array['mallCode']) ? $code_array['mallCode']  : '';
        } else {
            $mallCode =  '';
        }

        $mallName = $card_data['mallName'];
        $merchantID = $card_data['merchantID'];
        $merchantName = $card_data['merchantName'];

        try {

            if ( $is_transaction ) {
                DB::beginTransaction();
            }

            for ( $i = 0 ; $i < $send_num; $i++ ) {

                //随机生成券码
                $code = $this->createCode($activityID);

                $code_pool_obj = new CardCouponCode();
                $code_pool_obj->uuid = makeUuid();
                $code_pool_obj->timeStamp = Carbon::now();
                $code_pool_obj->creator = 'system';
                $code_pool_obj->createTime = Carbon::now();
                $code_pool_obj->barcode = $code;
                $code_pool_obj->code_type = $code_type;
                $code_pool_obj->pcustID = $pcustID;
                $code_pool_obj->custID = $custID;
                $code_pool_obj->cardNo = '';
                $code_pool_obj->member_code = $member_code;
                $code_pool_obj->member_code_type = $member_code_type;
                $code_pool_obj->nick_name = '';
                $code_pool_obj->activity_id = $activityID;
                $code_pool_obj->activity_uuid = $activityUUID;
                $code_pool_obj->external_code = $external_code;
                $code_pool_obj->activity_name = $activityName;
                $code_pool_obj->activity_start_time = $start_time;
                $code_pool_obj->activity_end_time = $end_time;
                $code_pool_obj->code_start_time = $code_startTime;
                $code_pool_obj->code_end_time = $code_endTime;
                $code_pool_obj->get_time = $get_time;
                $code_pool_obj->code_status = $code_status;
                $code_pool_obj->code_verify_type = $code_verify_type;
                $code_pool_obj->postID = $postID;
                $code_pool_obj->goods_name = $goods_name;
                $code_pool_obj->product_code = $product_code;
                $code_pool_obj->goods_num = $goods_num;
                $code_pool_obj->market_price = $marketPrice;
                $code_pool_obj->sale_price = $salePrice;
                $code_pool_obj->mall_id = $mallID;
                $code_pool_obj->mall_code = $mallCode;
                $code_pool_obj->mall_name = $mallName;
                $code_pool_obj->external_no = $external_code;
                $code_pool_obj->mobile = '';
                $code_pool_obj->bill_no = $bill_no;
                $code_pool_obj->sales_code = $sales_code;
                $code_pool_obj->code_amount = $code_amount;
                $code_pool_obj->code_use_amount = $code_use_amount;
                $code_pool_obj->code_limit_amount = $limitMoney;
                $code_pool_obj->code_discount = $discount;
                $code_pool_obj->code_use_type = $code_use_type;
                $code_pool_obj->merchantID = $merchantID;
                $code_pool_obj->merchantName = $merchantName;

                $code_pool_obj->save();

            }

            //更新卡券领取数量
            CardCoupon::where('card_id',$activityID)->increment('getNum', $send_num);

            Redis::incrBy('EBSIG_CARD_COUPON_GETED_'.$activityID,$send_num);

            if ($is_transaction) {
                DB::commit();
            }

            return ['code' => 200, 'message' => '卡券领取成功'];

        } catch (Exception $e) {

            if ($is_transaction) {
                DB::rollBack();
            }

            return ['code' => $e->getCode() , 'message' => $e->getMessage()];

        }

    }

}